package com.scm.servlet.login;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.scm.dao.CustomerDao;
import com.scm.dao.VenderDao;
import com.scm.model.Customer;
import com.scm.model.Vender;

@WebServlet("/customerlogin")
public class CustomerLoginServlet extends HttpServlet{
	private static final long serialVersionUID = -803701738257974937L;
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String account = req.getParameter("account");
		String password = req.getParameter("password");
		if(account == null || password == null || account.trim().equals("") || password.trim().equals("")){
			resp.sendRedirect(req.getContextPath()+"/login.jsp");
		}else{
			try {
				Customer customer = new CustomerDao().login(account,password);
				if(customer != null){
					req.getSession().setAttribute("user", customer);
					resp.sendRedirect(req.getContextPath()+"/index.htm");
					return ;
				}else{
					Vender vender = new VenderDao().login(account,password);
					if(vender != null) {
						req.getSession().setAttribute("user", vender);
						resp.sendRedirect(req.getContextPath()+"/index.htm");
						return ;
					}else {
						req.setAttribute("info", "用户名不存在或密码错误");
					}
				}
			} catch (SQLException e) {
				req.setAttribute("info", "数据库连接异常");
			}catch (Exception e) {
				req.setAttribute("info", "程序异常");
			}
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		}
	}
}
